package com.yhx.leetcode.java;

/**
 * @Author: mishuai
 * @Date: 2020/6/22 5:57 下午
 */
public class LeetCode4 {


    public static void main(String[] args) {
        //System.out.println(longestPalindrome("cccdddd"));

    }


    //1.暴力求解
    public static String longestPalindrome(String str) {
        if(str.isEmpty() || str.length() == 1){
            return str;
        }
        if(str.length() == 2 && str.charAt(0) == str.charAt(1)){
            return str;
        }
        String st="";
        for(int i=0; i <str.length();i++){
            for(int j=i;j<=str.length();j++){
                String temp=str.substring(i,j);
                if(isHuiwen(temp) && temp.length()>st.length() ){
                    st=temp;
                }
            }
        }
        return st;
    }



    public static boolean isHuiwen(String str){
        char c[]=str.toCharArray();
        for(int i=0;i<str.length()/2;i++){
            if(c[i] != c[str.length() - i -1]){
                return false;
            }
        }
        return true;
    }

    //=========================================================================================//

    //中心扩展法向两边扩张
    public static String longestPalindrome1(String s) {
        if (s == null || s.length() < 1) return "";
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {

            int len1 = expandAroundCenter(s, i, i);
            int len2 = expandAroundCenter(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    private static int expandAroundCenter(String s, int left, int right) {
        int L = left, R = right;
        while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
            L--;
            R++;
        }
        return R - L - 1;
    }
}
